package com.ftg.learn.chapter10.jdbc;


import java.sql.*;
import java.util.Objects;

/**
 * @author kangjx
 * @createTime 2022/7/19
 */
public class LearnJdbc {


    //四个基本信息
    private static String username ="root";
    private static String password ="Love0913@kjx";
    private static String host = "127.0.0.1";
    private static String port = "3306";
    private static String databaseName = "cool2204";
    private static String driverClass = "com.mysql.cj.jdbc.Driver";


    public static void main(String[] args) {
        //1、加载驱动类
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        //try with resources
        try {
            //第一种  反射 mysql 8
            Class.forName(driverClass);

//            //第二种
//            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

            String url = "jdbc:mysql://"+host+":"+port+"/"+databaseName+"?serverTimezone=UTC";
            conn = DriverManager.getConnection(url,username,password);
            stmt = conn.createStatement();
            String sql = "select sno,sname,ssex,sage from student";
            rs = stmt.executeQuery(sql);
            while (rs.next()){
                String sno = rs.getString(1);
                String sname = rs.getString(2);
                String ssex = rs.getString(3);
                int sage = rs.getInt(4);
                System.out.println("学号是:" + sno +"\t 姓名是:"+sname+"\t 年龄是:"+sage+"\t 性别是:"+ssex);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally{
            if(Objects.isNull(conn)){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(Objects.isNull(stmt)){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(Objects.isNull(rs)){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }
//        Connection  会话
//        Statement   静态sql
//        PreparedStatement 预编译
//        ResultSet 结果集
    }


}
